﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Catering.View_Operaction;
using System.Data;
using System.Web.Services;
using System.Collections;

namespace Catering.Catering_Page.Kufang
{
    public partial class Ckgl : UserIsNull
    {
        Catering_Rules.FromRecords CR_Frds = new Catering_Rules.FromRecords();
        Catering.View_Operaction_Common voc = new View_Operaction_Common();
        public int m_sel_index_zyq = 0;
        public int m_sel_index_bz = 0;
        public string m_kf = "-1";
        public string m_an = "";
        public string m_chaxun = "";
        public int m_pageNum = 1;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                #region 获取参数

                if (Request.QueryString["sel_index_zyq"] != null) m_sel_index_zyq = Convert.ToInt32(Request.QueryString["sel_index_zyq"]);
                if (Request.QueryString["sel_index_bz"] != null) m_sel_index_bz = Convert.ToInt32(Request.QueryString["sel_index_bz"]);
                if (Request.QueryString["m_kf"] != null) m_kf = Request.QueryString["m_kf"].ToString();
                if (Request.QueryString["m_an"] != null) m_an = Request.QueryString["m_an"].ToString();
                if (Request.QueryString["m_chaxun"] != null) m_chaxun = Request.QueryString["m_chaxun"].ToString();
                if (Request.QueryString["Page"] != null)
                {
                    string temppage = Request.QueryString["Page"].ToString();
                    Int32.TryParse(temppage, out m_pageNum);
                }
                #endregion

                Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                this.LoadData();
                this.but_Seach_Click(null, null);
                this.Txt_riqi.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy-MM-dd',maxDate:'%y-%M-%d'})");
                if (!string.IsNullOrEmpty(Toolss.GetCookie("ckgl_AddTime"))) this.Txt_riqi.Text = Toolss.GetCookie("ckgl_AddTime");

            }
        }

        //加载页面数据
        public void LoadData()
        {
            if (Session["User"] != null)
            {
                string userid = Session["PersonnelID"].ToString();
                int companyid = 0;
                int groupid = 0;
                int classid = 0;
                bool isAdmin = false;
                Bind_Data_to_Controls.GetCompanyByCurrentUser(userid, out companyid, out groupid, out classid, out isAdmin);
                //if (isAdmin)
                //{
                //    voc.DropDownListDataBind_Group(DDL_zuoyequ, companyid);
                //    voc.DropDownListDataBind_Class(DDL_banzu, DDL_zuoyequ.Items[0].Value);
                //}
                //else
                //{
                Bind_Data_to_Controls.Bind_Area_ddl(DDL_zuoyequ, isAdmin, groupid, companyid, false, false);
                //Bind_Data_to_Controls.Bind_Class_ddl(DDL_zuoyequ.SelectedItem, DDL_banzu, isAdmin, classid, false);
                //}

                DataTable dt_kufang = new Catering_Rules.StorageRoom().GetAllList().Tables[0];
                this.DDL_kufang.LoadDrop(dt_kufang, "id", "RoomID", true);

                this.DDL_zuoyequ.SelectedIndex = m_sel_index_zyq;
                Bind_Data_to_Controls.Bind_Class_ddl(DDL_zuoyequ.SelectedItem, DDL_banzu, isAdmin, classid, false);
                this.DDL_banzu.SelectedIndex = m_sel_index_bz;
                this.DDL_kufang.SelectedValue = m_kf;

                if (m_an != "")
                {
                    this.DDL_an.SelectedValue = m_an;
                    this.TB_chaxun.Text = m_chaxun;
                }
                else
                {
                    this.DDL_an.SelectedValue = "OutDate";
                    this.TB_chaxun.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy-MM-dd',maxDate:'%y-%M-%d'})");
                    this.TB_chaxun.Text = DateTime.Now.ToString("yyyy-MM-dd");
                    //this.TB_chaxun.Text = GetLastDate(this.DDL_zuoyequ.SelectedValue, this.DDL_banzu.SelectedValue, this.DDL_kufang.SelectedValue, this.DDL_an.SelectedValue, this.TB_chaxun.Text.Trim());
                }
            }

        }

        //搜索
        protected void but_Seach_Click(object sender, EventArgs e)
        {
            DataTable dt = this.GetFromRecords(this.DDL_zuoyequ.SelectedValue,
            this.DDL_banzu.SelectedValue, this.DDL_an.SelectedValue, this.TB_chaxun.Text.Trim(), this.DDL_kufang.SelectedValue);

            Session["RepeatTable"] = dt;
            int pagecurrent = 0;
            if (sender != null) pagecurrent = 1;
            Lbl_FromRecodesNum.Text = "0";
            new View_Operaction_Common().RepeaterDataBind(dt, Repeater1, Request, 20, lblCurPage, InkPrev, InkLast, InkFirst, InkNext, GetURL(1), "Ckgl.aspx", pagecurrent);
            if (dt != null && dt.Rows.Count > 0)
            {
                var result = from b in dt.AsEnumerable() select new { money = b[10] };
                Lbl_FromRecodesNum.Text = result.Sum(p => Convert.ToDecimal(p.money)).ToString();
            }
            this.HF_URL.Value = GetURL(0);
        }

        public DataTable GetFromRecords(string strGroupID, string strClassID, string strSelect, string strSeachContent, string strDBID)
        {
            DataTable dt = new DataTable();
            View_Operaction_Common voc = new View_Operaction_Common();

            string str = "GroupID= " + strGroupID + " and ClassID= " + strClassID;
            if (strDBID != "-10")
            {
                str += " and DBID=" + strDBID;
            }

            if (!string.IsNullOrEmpty(strSeachContent.Trim()))
            {
                switch (strSelect)
                {
                    case "OutDate":
                        DateTime addDate = DateTime.Now;
                        DateTime.TryParse(strSeachContent, out addDate);
                        str = str + "  and year(OutDate)=" + addDate.Year + " and month(OutDate)=" + addDate.Month + " and day(OutDate)=" + addDate.Day;
                        break;
                    case "RAWID":
                        str = str + "  and  InDBid  like '%" + strSeachContent + "%'";
                        break;
                    case "RAWName":
                        str = str + "  and  RAWName like'" + strSeachContent + "%'";
                        break;
                    case "RAWTID":
                        DataTable dt_RawMaterials = new Catering_Rules.T_RawMaterials().GetList("TypeName like '%" + strSeachContent + "%'").Tables[0];
                        string idlist = "";
                        foreach (DataRow row in dt_RawMaterials.Rows)
                        {
                            idlist += row["id"].ToString() + ",";
                        }
                        if (idlist != "")
                        {
                            str += " and RAWTID in (" + idlist.TrimEnd(',') + ")";
                        }
                        else
                        {
                            str += " and 1=2";
                        }
                        break;
                    case "RAWIDs":
                        DataTable dt_RawMaterialsInfo = new Catering_Rules.RawMaterialsInfo().GetList("Name like '%" + strSeachContent + "%'").Tables[0];
                        string idlist2 = "";
                        foreach (DataRow row in dt_RawMaterialsInfo.Rows)
                        {
                            idlist2 += row["id"].ToString() + ",";
                        }
                        if (idlist2 != "")
                        {
                            str += " and RAWIDs in (" + idlist2.TrimEnd(',') + ")";
                        }
                        else
                        {
                            str += " and 1=2";
                        }
                        break;
                }
            }

            DataSet ds = new Catering_Rules.FromRecords().GetList(str);
            if (ds != null && ds.Tables.Count > 0)
            {
                if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                {
                    dt = ds.Tables[0];
                }
            }
            return dt;
        }

        /// <summary>
        /// 根据条件获取最新数据的时间
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public string GetLastDate(string strGroupID, string strClassID, string strDBID, string strSelect, string strSeachContent)
        {
            string str = " AND GroupID= " + strGroupID + " AND ClassID= " + strClassID;
            if (strDBID != "-1") str += " AND DBID=" + strDBID;
            return Convert.ToDateTime(new Catering_Rules.FromRecords().GetLastDate(str)).ToString("yyyy-MM-dd");
        }

        //月份提交
        protected void Button2_Click(object sender, EventArgs e)
        {
            DateTime dtime = DateTime.Now;
            if (this.DDL_an.SelectedValue == "OutDate" && !string.IsNullOrEmpty(this.TB_chaxun.Text))
            {
                DateTime.TryParse(this.TB_chaxun.Text, out dtime);
            }
            DateTime starttime = Convert.ToDateTime(dtime.Year.ToString() + "-" + dtime.Month.ToString() + "-01");
            DateTime endTime;
            if (dtime.Month == 12)
            {
                endTime = Convert.ToDateTime((dtime.Year + 1).ToString() + "-" + "01-01");
            }
            else
            {
                endTime = Convert.ToDateTime(dtime.Year.ToString() + "-" + (dtime.Month + 1).ToString() + "-01");
            }

            string strwhere = " ClassID=" + Convert.ToInt32(this.DDL_banzu.SelectedValue) + " AND convert(datetime,OutDate)>=convert(datetime,'" + starttime.ToShortDateString() + "') and convert(datetime,OutDate)<convert(datetime,'" + endTime.ToShortDateString() + "')";
            DataTable dt_Monitor = new Catering_Rules.Monitor().GetList(strwhere).Tables[0];
            if (dt_Monitor != null && dt_Monitor.Rows.Count > 0)
            {
                View_Operaction_Common.Show(this, "不能重复提交！");
            }
            else
            {
                Catering_Model.Monitor cmm = new Catering_Model.Monitor();
                cmm.id = new Catering_Rules.Monitor().GetMaxId();
                cmm.GroupID = Convert.ToInt32(this.DDL_zuoyequ.SelectedValue);
                cmm.ClassID = Convert.ToInt32(this.DDL_banzu.SelectedValue);
                cmm.OutState = "1";
                cmm.OutDate = dtime.ToShortDateString();
                new Catering_Rules.Monitor().Add(cmm);
                View_Operaction_Common.Show(this, "提交成功");
            }
        }

        //变更查询条件
        protected void DDL_an_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.TB_chaxun.Text = "";
            if (DDL_an.SelectedIndex == 4)
            {
                this.TB_chaxun.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy-MM-dd',maxDate:'%y-%M-%d'})");
            }
            else
            {
                this.TB_chaxun.Attributes.Clear();
            }
        }

        protected void DDL_zuoyequ_SelectedIndexChanged(object sender, EventArgs e)
        {
            voc.DropDownListDataBind_Class(DDL_banzu, DDL_zuoyequ.SelectedValue);
            this.DDL_banzu.SelectedIndex = 0;
        }

        protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            DataRowView drv = (DataRowView)e.Item.DataItem;
            Catering_Model.E_RawMaterial cmrm = new Catering_Rules.T_RawMaterial().GetModel(Convert.ToInt32(drv["RAWID"]));
            if (cmrm == null)
            {
                drv["RAWID"] = 1;
            }

        }

        //验证出库数量
        [WebMethod]
        public static ArrayList Raw_outpu_wring(string strMaxtype)
        {
            ArrayList al = new ArrayList();
            string[] strs = strMaxtype.Trim().Split(',');
            DataTable dt = new Catering_Rules.RawMaterial_Area().GetList("InDBid='" + strs[3] + "'").Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                string strwhere = "ClassID=" + strs[1] + " and RAWID=" + dt.Rows[0]["RawID"].ToString();
                DataTable dt_RoomWaing = new Catering_Rules.RoomWaing().GetList(strwhere).Tables[0];
                if (dt_RoomWaing != null && dt_RoomWaing.Rows.Count > 0)
                {
                    al.Add("OK");
                    al.Add(dt_RoomWaing.Rows[0]["MinContent"].ToString());
                }
            }
            else
            {
                al.Add("NO");
            }
            return al;
        }

        //出库
        [WebMethod]
        public static ArrayList rkgl_add(string strMaxtype)
        {
            ArrayList list = new ArrayList();
            string[] s = strMaxtype.Split(',');
            DateTime dtime = Convert.ToDateTime(s[4]);
            int classid = 0;
            Int32.TryParse(s[1], out classid);
            //DateTime starttime = Convert.ToDateTime(dtime.Year.ToString() + "-" + dtime.Month.ToString() + "-01");
            //DateTime endTime;
            ////if (dtime.Month == 12)
            //{
            //    endTime = Convert.ToDateTime((dtime.Year + 1).ToString() + "-" + "01-01");
            //}
            //else
            //{
            //    endTime = Convert.ToDateTime(dtime.Year.ToString() + "-" + (dtime.Month + 1).ToString() + "-01");
            //}

            //string strwhere = " ClassID=" + classid + " AND convert(datetime,OutDate)>=convert(datetime,'" + starttime.ToShortDateString() + "') and convert(datetime,OutDate)<convert(datetime,'" + endTime.ToShortDateString() + "')";
            //DataTable dt_Monitor = new Catering_Rules.Monitor().GetList(strwhere).Tables[0];
            //if (dt_Monitor != null && dt_Monitor.Rows.Count > 0)
            //{
            //    list.Add("NO");
            //}
            //else
            //{
            DataTable dt_Raw_A = new Catering_Rules.RawMaterial_Area().GetList("InDBid='" + s[3] + "'").Tables[0];
            Catering_Model.E_RawMaterial md_Raw = new Catering_Rules.T_RawMaterial().GetModel(Convert.ToInt32(dt_Raw_A.Rows[0]["RawID"].ToString()));
            Catering_Model.FromRecords md = new Catering_Model.FromRecords();
            decimal number = 0;
            Decimal.TryParse(s[5], out number);
            string unit = new Catering_Rules.Units().GetModel(Convert.ToInt32(md_Raw.temp2)).UName;
            string currentunit = s[8];
            if (unit != currentunit)
            {
                DataTable dt_RMUnit1 = new Catering_Rules.RawMaterial_Unit().GetUnitByRawMaterialID(md_Raw.id).Tables[0];

                List<decimal> danweiguige = new List<decimal>();
                List<string> danweiguigeName = new List<string>();
                int biaozhun = 0;
                int current = 0;
                if (dt_RMUnit1 != null && dt_RMUnit1.Rows.Count > 0)
                {
                    for (int i = 0; i < dt_RMUnit1.Rows.Count; i++)
                    {
                        decimal tempnum = Convert.ToDecimal(dt_RMUnit1.Rows[i]["Number"]);
                        string danwei = dt_RMUnit1.Rows[i]["UName"].ToString();
                        if (danwei == unit) biaozhun = i;
                        if (danwei == currentunit) current = i;
                        danweiguige.Add(tempnum);
                        danweiguigeName.Add(danwei);
                    }
                    dt_RMUnit1.Dispose();
                    decimal fun = 1;
                    if (biaozhun > current)
                    {
                        for (int i = (current + 1); i <= biaozhun; i++)
                        {
                            fun = danweiguige[i] * fun;
                        }
                        number = Toolss.GetMathResult((number * fun), 2, 3);
                    }
                    else if (biaozhun < current)
                    {
                        for (int i = current; i > biaozhun; i--)
                        {
                            fun = danweiguige[i] * fun;
                        }
                        number = Toolss.GetMathResult((number / fun), 2, 3);
                    }
                }
            }
            md.id = new Catering_Rules.FromRecords().GetMaxId();
            md.GroupID = Convert.ToInt32(s[0]);
            md.ClassID = Convert.ToInt32(s[1]);
            md.DBID = md_Raw.RAWTID;
            md.RAWTID = md_Raw.RAWID;
            md.RAWIDs = md_Raw.RAWIDS;
            md.RAWID = md_Raw.id;
            md.RAWName = md_Raw.RAWName;
            md.Price = Convert.ToDecimal(s[7]);
            md.Numbers = number.ToString();
            md.AmountMoney = Convert.ToDecimal(s[11]);
            md.CMP = unit;
            md.OutDate = Convert.ToDateTime(s[4]);
            md.Back = s[6];

            md.Specifications = s[9];
            md.InDBid = s[3];
            md.temp1 = "0";
            md.temp2 = "";
            decimal sum = Convert.ToDecimal(md.Numbers);//总重量

            #region old

            ////计算出库总量（仅限于[禽肉类：3、鱼虾类：4、蔬菜类：6、水果类：7、谷类薯类及杂豆：8、盐：11]）
            //if (md_Raw.RAWZS == 3 || md_Raw.RAWZS == 4 || md_Raw.RAWZS == 6 || md_Raw.RAWZS == 7 || md_Raw.RAWZS == 8 || md_Raw.RAWZS == 11)
            //{
            //    //获取规格
            //    DataTable dt_RMUnit = new Catering_Rules.RawMaterial_Unit().GetUnitByRawMaterialID(md_Raw.id).Tables[0];

            //    if (dt_RMUnit != null && dt_RMUnit.Rows.Count > 0)
            //    {
            //        bool isJiSuan = false;
            //        for (int i = 0; i < dt_RMUnit.Rows.Count; i++)
            //        {
            //            decimal tempnum = Convert.ToDecimal(dt_RMUnit.Rows[i]["Number"]);
            //            string danwei = dt_RMUnit.Rows[i]["UName"].ToString();
            //            if (tempnum > 0 && isJiSuan) sum = sum * tempnum;
            //            if (!isJiSuan && danwei == md.CMP) isJiSuan = true;
            //        }
            //        dt_RMUnit.Dispose();
            //    }

            //}
            //if (md_Raw.RAWZS == 10)//油类
            //{
            //    //获取规格
            //    DataTable dt_RMUnit = new Catering_Rules.RawMaterial_Unit().GetUnitByRawMaterialID(md_Raw.id).Tables[0];

            //    if (dt_RMUnit != null && dt_RMUnit.Rows.Count > 0)
            //    {
            //        bool isJiSuan = false;
            //        string lastutil = "";
            //        for (int i = 0; i < dt_RMUnit.Rows.Count; i++)
            //        {
            //            decimal tempnum = Convert.ToDecimal(dt_RMUnit.Rows[i]["Number"]);
            //            string danwei = dt_RMUnit.Rows[i]["UName"].ToString();
            //            if (!string.IsNullOrEmpty(danwei))
            //            {
            //                if (tempnum > 0 && isJiSuan) sum = sum * tempnum;
            //                if (!isJiSuan && danwei == md.CMP) isJiSuan = true;
            //                lastutil = danwei;
            //            }
            //        }
            //        dt_RMUnit.Dispose();
            //        if (lastutil == "升") sum = sum * 920;
            //        if (lastutil == "毫升") sum = sum * decimal.Parse("0.92");
            //    }
            //}

            #endregion

            bool iskg = true;
            decimal guige = 1;
            decimal UtilKg = Toolss.GetSpecifications(Convert.ToInt32(md.RAWID), md.CMP, out iskg);
            guige = iskg ? 1000 : 1;
            decimal weight = Toolss.GetMathResult(UtilKg * sum, 2, 3);
            md.SumNumber = weight * guige;
            ArrayList cal = new Catering_Rules.FromRecords().CanbeFromRecords(md);
            if (cal != null && cal[0].ToString() != "OK")
            {
                list.Add(cal[1]);
            }
            else
            {
                int result = new Catering_Rules.BalanceInfo().AddFromRecords(md_Raw.id, Convert.ToInt32(s[1]), s[3], md.OutDate, md.Numbers, "", md.id);
                if (result == 3)
                {
                    new Catering_Rules.FromRecords().Add(md);
                    Toolss.WriteCookie("ckgl_AddTime", md.OutDate.ToString("yyyy-MM-dd"));
                    list.Add("OK");
                }
                else
                {
                    list.Add("Other");
                }
            }
            //}

            return list;
        }

        //删除出库记录
        [WebMethod]
        public static string rkgl_Del(string strID)
        {
            int result = new Catering_Rules.BalanceInfo().DelFromRecords(Convert.ToInt32(strID));
            if (result == 3)
            {
                new Catering_Rules.FromRecords().Delete(Convert.ToInt32(strID));
                return "OK";
            }
            return "NO";
        }

        //根据品号查找对应原料信息
        [WebMethod]
        public static ArrayList InputRoomRawID_Chanage(string strID)
        {
            string[] infos = strID.Split(',');
            string str = "GroupID= " + infos[0] + " and ClassID= " + infos[1];

            DataTable dt_RawArea = new Catering_Rules.RawMaterial_Area().GetList(" InDBid='" + infos[2] + "'").Tables[0];

            //object obj_RawID = Toolss.GetSingle("RawMaterial_Area", "RawID", "InDBid='" + infos[2] + "'");

            if (dt_RawArea != null && dt_RawArea.Rows.Count > 0)
            {
                ArrayList list = new ArrayList();
                bool isbreak = false;
                for (int k = 0; k < dt_RawArea.Rows.Count; k++)
                {
                    list.Clear();
                    list.Add("OK");
                    string RawID = dt_RawArea.Rows[k]["RawID"].ToString();

                    Catering_Model.E_RawMaterial cmrm = new Catering_Rules.T_RawMaterial().GetModel(Convert.ToInt32(RawID));
                    str = str + "and RAWID= " + cmrm.id;
                    list.Add(cmrm.RAWName);//名称
                    ArrayList al = new Catering_Rules.BalanceInfo().GetLastBalanceInfo(infos[1], RawID, infos[2]);
                    if (al != null && al.Count >= 3)
                    {
                        list.Add(decimal.Round(Convert.ToDecimal(al[2]), 2));//单价
                        list.Add(decimal.Round(Convert.ToDecimal(al[1]), 2));// 当前库存
                        list.Add(decimal.Round(Convert.ToDecimal(al[1]) * Convert.ToDecimal(al[2]), 2));//总金额
                        isbreak = true;
                    }
                    else if (k < (dt_RawArea.Rows.Count - 1))
                    {
                        continue;
                    }
                    else
                    {
                        list.Add("");
                        list.Add("");
                        list.Add("");
                    }
                    string unit = new Catering_Rules.Units().GetModel(Convert.ToInt32(cmrm.temp2)).UName;
                    list.Add(unit);//单位
                    list.Add(Toolss.GetGuiGeByRawID(cmrm.id.ToString()));//规格

                    //获取规格
                    DataTable dt_RMUnit = new Catering_Rules.RawMaterial_Unit().GetUnitByRawMaterialID(cmrm.id).Tables[0];
                    string strunit = "<option value='1'>" + new Catering_Rules.Units().GetModel(Convert.ToInt32(cmrm.temp2)).UName + "</option>";
                    decimal tempjisuan = 1;
                    decimal tempjisuan1 = 1;
                    bool isstart = false;//是否开始计算
                    decimal danweinum = 1;//单位数量
                    List<decimal> danweiguige = new List<decimal>();
                    List<string> danweiguigeName = new List<string>();
                    if (dt_RMUnit != null && dt_RMUnit.Rows.Count > 0)
                    {
                        strunit = "";
                        for (int i = 0; i < dt_RMUnit.Rows.Count; i++)
                        {
                            decimal tempnum = Convert.ToDecimal(dt_RMUnit.Rows[i]["Number"]);
                            string danwei = dt_RMUnit.Rows[i]["UName"].ToString();

                            //从单位开始计算并记录单位规格数量
                            if (danwei == unit)
                            {
                                isstart = true;
                                danweinum = tempnum;
                                if (danweiguigeName.Count > 0)
                                {
                                    for (int j = 0; j < danweiguigeName.Count; j++)
                                    {
                                        string tempName = danweiguigeName[j];
                                        decimal tempguige1 = 1;
                                        for (int n = (j + 1); n < danweiguige.Count; n++)
                                        {
                                            tempguige1 = tempguige1 * danweiguige[n];
                                        }
                                        strunit += "<option value='-" + (tempguige1 * tempnum) + "'>" + tempName + "</option>";
                                    }
                                }
                            }
                            if (isstart)
                            {
                                if (danwei != unit)
                                {
                                    tempjisuan = tempjisuan * tempnum;
                                    strunit += "<option value='" + tempjisuan + "'>" + danwei + "</option>";
                                }
                                else
                                {
                                    strunit += "<option selected='selected' value='" + tempjisuan + "'>" + danwei + "</option>";
                                }
                            }
                            else//未开始计算
                            {
                                tempjisuan1 = tempjisuan1 * tempnum;
                                danweiguige.Add(tempjisuan1);
                                danweiguigeName.Add(danwei);
                            }
                        }
                        dt_RMUnit.Dispose();
                    }
                    list.Add(strunit);

                    //list.Add(new Catering_Rules.RawMaterials().GetModel(cmrm.RAWID).TypeName);//大类
                    //list.Add(new Catering_Rules.RawMaterialsInfo().GetModel(cmrm.RAWIDS).Name);//小类
                    if (isbreak) break;
                }
                dt_RawArea.Dispose();
                return list;
            }
            else
            {
                ArrayList list = new ArrayList();
                list.Add("NO");
                return list;
            }
        }

        //根据品名查找对于原料信息
        [WebMethod]
        public static ArrayList InputRoomRawName_Chanage(string strID)
        {

            string[] infos = strID.Split(',');
            string str = "GroupID= " + infos[0] + " and ClassID= " + infos[1];

            DataTable dt_RawMaterial = new Catering_Rules.T_RawMaterial().GetList("RAWName='" + infos[2] + "'").Tables[0];

            if (dt_RawMaterial != null && dt_RawMaterial.Rows.Count > 0)
            {
                ArrayList list = new ArrayList();
                bool isbreak = false;
                for (int k = 0; k < dt_RawMaterial.Rows.Count; k++)
                {
                    list.Clear();
                    list.Add("OK");
                    string RawID = dt_RawMaterial.Rows[0]["id"].ToString();
                    Catering_Model.E_RawMaterial cmrm = new Catering_Rules.T_RawMaterial().GetModel(Convert.ToInt32(RawID));
                    str = str + "and RAWID= " + cmrm.id;
                    DataTable dt_RawMaterial_Area = new Catering_Rules.RawMaterial_Area().GetList("RawID=" + RawID).Tables[0];
                    string InDBid = "";
                    if (dt_RawMaterial_Area != null && dt_RawMaterial_Area.Rows.Count > 0)
                    {
                        InDBid = dt_RawMaterial_Area.Rows[0]["InDBid"].ToString();
                        list.Add(InDBid);//品号
                    }
                    else
                    {
                        list.Add("");
                    }
                    ArrayList al = new Catering_Rules.BalanceInfo().GetLastBalanceInfo(infos[1], RawID, InDBid);
                    if (al != null && al.Count >= 3)
                    {
                        list.Add(decimal.Round(Convert.ToDecimal(al[2]), 2));//单价
                        list.Add(decimal.Round(Convert.ToDecimal(al[1]), 2));// 当前库存
                        list.Add(decimal.Round(Convert.ToDecimal(al[1]) * Convert.ToDecimal(al[2]), 2));//总金额
                        isbreak = true;
                    }
                    else if (k < (dt_RawMaterial.Rows.Count - 1))
                    {
                        continue;
                    }
                    else
                    {
                        list.Add("");
                        list.Add("");
                        list.Add("");
                    }
                    string unit = new Catering_Rules.Units().GetModel(Convert.ToInt32(cmrm.temp2)).UName;
                    list.Add(unit);//单位
                    list.Add(Toolss.GetGuiGeByRawID(cmrm.id.ToString()));//规格


                    //获取规格
                    DataTable dt_RMUnit = new Catering_Rules.RawMaterial_Unit().GetUnitByRawMaterialID(cmrm.id).Tables[0];
                    string strunit = "<option value='1'>" + new Catering_Rules.Units().GetModel(Convert.ToInt32(cmrm.temp2)).UName + "</option>";
                    decimal tempjisuan = 1;
                    decimal tempjisuan1 = 1;
                    bool isstart = false;//是否开始计算
                    decimal danweinum = 1;//单位数量
                    List<decimal> danweiguige = new List<decimal>();
                    List<string> danweiguigeName = new List<string>();
                    if (dt_RMUnit != null && dt_RMUnit.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt_RMUnit.Rows.Count; i++)
                        {
                            decimal tempnum = Convert.ToDecimal(dt_RMUnit.Rows[i]["Number"]);
                            string danwei = dt_RMUnit.Rows[i]["UName"].ToString();

                            //从单位开始计算并记录单位规格数量
                            if (danwei == unit)
                            {
                                isstart = true;
                                danweinum = tempnum;
                                if (danweiguigeName.Count > 0)
                                {
                                    for (int j = 0; j < danweiguigeName.Count; j++)
                                    {
                                        string tempName = danweiguigeName[j];
                                        decimal tempguige1 = 1;
                                        for (int n = (j + 1); n < danweiguige.Count; n++)
                                        {
                                            tempguige1 = tempguige1 * danweiguige[n];
                                        }
                                        strunit += "<option value='-" + (tempguige1 * tempnum) + "'>" + tempName + "</option>";
                                    }
                                }
                            }
                            if (isstart)
                            {
                                if (danwei != unit)
                                {
                                    tempjisuan = tempjisuan * tempnum;
                                    strunit += "<option value='" + tempjisuan + "'>" + danwei + "</option>";
                                }
                                else
                                {
                                    strunit += "<option selected='selected' value='" + tempjisuan + "'>" + danwei + "</option>";
                                }
                            }
                            else//未开始计算
                            {
                                tempjisuan1 = tempjisuan1 * tempnum;
                                danweiguige.Add(tempjisuan1);
                                danweiguigeName.Add(danwei);
                            }
                        }
                    }
                    list.Add(strunit);
                    if (isbreak) break;
                    //list.Add(new Catering_Rules.RawMaterials().GetModel(cmrm.RAWID).TypeName);//大类
                    //list.Add(new Catering_Rules.RawMaterialsInfo().GetModel(cmrm.RAWIDS).Name);//小类
                }
                dt_RawMaterial.Dispose();
                return list;
            }
            else
            {
                ArrayList list = new ArrayList();
                list.Add("NO");
                return list;
            }
        }

        /// <summary>
        /// 获取可出库量
        /// </summary>
        /// <param name="StrClassID"></param>
        /// <param name="InDBID"></param>
        /// <param name="SearchDate"></param>
        /// <returns></returns>
        [WebMethod]
        public static ArrayList Get_CkBalance(string StrClassID,string InDBID, string SearchDate)
        {
            DateTime dtime = DateTime.MinValue;
            int classid = 0;
            ArrayList al = new ArrayList();

            if (string.IsNullOrEmpty(SearchDate) || string.IsNullOrEmpty(InDBID))
            {
                al.Add("NotNull");
                return al;
            }
            DateTime.TryParse(SearchDate, out dtime);
            Int32.TryParse(StrClassID, out classid);
            if (dtime.Year < 1949)
            {
                al.Add("ErrorDate");
                return al;            
            }
            if (classid<=0)
            {
                al.Add("ErrorClass");
                return al;
            }
            dtime = new DateTime(dtime.Year, dtime.Month, dtime.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            //获取可出库数量
            decimal sechbalance = new Catering_Rules.BalanceInfo().GetBalance(classid, InDBID, dtime);
            al.Add("OK");
            al.Add(sechbalance);
            return al;
        }

        public int i = 0;
        public string GetXuNiIndex()
        {
            if (i == 0)
            {
                i = (((m_pageNum - 1) * 10) + 1);
            }
            else
            {
                i += 1;
            }
            return i.ToString();
        }

        public string GetKuFang(string DBID)
        {
            string NAME = "";
            if (!string.IsNullOrEmpty(DBID))
            {
                NAME = new Catering_Rules.StorageRoom().GetModel(Convert.ToInt32(DBID)).RoomID;
            }
            return NAME;
        }

        /// <summary>
        /// 返回url，包含参数
        /// </summary>
        /// <param name="state">0：包含页数、1：不包含页数</param>
        /// <returns></returns>
        public string GetURL(int state)
        {
            string result = "Ckgl.aspx?sel_index_zyq=" + this.DDL_zuoyequ.SelectedIndex;
            result += "&sel_index_bz=" + this.DDL_banzu.SelectedIndex;
            if (this.DDL_kufang.SelectedValue != "-1") result += "&m_kf=" + this.DDL_kufang.SelectedValue;
            result += "&m_an=" + this.DDL_an.SelectedValue;
            result += "&m_chaxun=" + this.TB_chaxun.Text.Trim();
            if (state == 0) result += "&Page=" + m_pageNum;
            return result.ToString();
        }

        public bool IsAdmin()
        {
            if (Session["RoleID"] != null && !string.IsNullOrEmpty(Session["RoleID"].ToString()))
            {
                int role = 0;
                Int32.TryParse(Session["RoleID"].ToString(), out role);
                Catering_Model.Role model = new Catering_Rules.Role().GetModel(role);
                if (model != null && model.temp1 > 5) return true;
            }
            return false;
        }

    }
}